#pragma once

#include <iostream>
#include <string>
#include <unordered_map>
#include <fstream>
#include "Log.hpp"

using namespace std;

namespace dict_ns
{
    const string sep = ": ";
    const string defaultpath = "./Dict.txt";
    class Dict
    {
    private:
        bool Load()
        {
            ifstream in(_filepath);
            if (!in.is_open())
            {
                Log(FATAL, "open %s error!", _filepath);
                return false;
            }
            // 从文件中获取字典，并且存入内存中
            string line;
            while (getline(in, line))
            {
                if (line.empty())
                    continue;
                int pos = line.find(sep);
                if (pos == string::npos)
                    continue;
                string word = line.substr(0, pos); //   前闭后开
                if (word.empty())
                    continue;
                string han = line.substr(pos + sep.size());
                if (han.empty())
                    continue;
                Log(DEBUG, "load info, %s: %s\n", word.c_str(), han.c_str());
                // 存入内存中
                _dict.insert(make_pair(word, han));
            }
            Log(INFO, "Init Dict success!");
            return true;
        }

    public:
        Dict(string filepath = defaultpath) : _filepath(filepath)
        {
            if (Load())
            {
                Log(INFO, "Dict Load success!");
            }
            Log(ERROR, "Dict Load error !");
        }
        string Translate(const string &word,bool &ok)
        {
            ok=true;
            auto pos = _dict.find(word);
            if (pos == _dict.end())
            {
                cout << "Find " << word << " error" << endl;
                return "未找到";
            }

            // return _dict[word];//二选一
            return pos->second;
        }
        ~Dict() {}

    private:
        string _filepath;
        unordered_map<string, string> _dict;
    };
}